<template>
  <div>
    <el-upload multiple action="" list-type="picture-card" drag :class="{disabledUpload: disabledUpload}"
               :file-list="images"
               :disabled="disabled"
               :on-success="imageSuccess"
               :http-request="uploadImages"
               :on-remove="removeImage"
               :on-preview="imagePreview">
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-dialog append-to-body :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl">
    </el-dialog>
  </div>
</template>

<script>
import aliOss from '@/utils/aliOss'

export default {
  data() {
    return {
      images: [],
      imagesUrl: [],
      dialogVisible: false,
      dialogImageUrl: '',
    }
  },
  props: {
    disabled: false,
  },
  computed: {
    disabledUpload() {
      return (!this.$attrs.hasOwnProperty('multiple')) && (this.images.length > 0)
    }
  },
  watch: {
    '$attrs.value': {
      immediate: true,
      handler(images) {
        if (this.$attrs.hasOwnProperty('multiple')) {
          if (images && images.length > 0) {
            // setTimeout(() => {
            //   this.images = images.map(url => ({url}))
            // },500)
          } else {
            this.images = []
          }
        } else {
          if (images) {
            setTimeout(() => {
              this.images = [images].map(url => ({url}))
            },500)
          } else {
            this.images = []
          }
        }
      }
    }
  },
  methods: {
    async uploadImages(file) {
      return aliOss.ossUploadFile(file, 'image')
      // return new Promise((resolve => resolve()))
    },
    imageSuccess(res, file, fileList) {
      this.imagesUrl = fileList.map(file => file.response && file.response.data || file.name)
      this.images = fileList
      if (this.$attrs.hasOwnProperty('multiple')) {
        this.$emit('input', this.imagesUrl)
      } else {
        this.$emit('input', this.imagesUrl[0])
      }
    },
    imagePreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    removeImage(file, fileList) {
      this.images = fileList
      this.imagesUrl = fileList.map(file => file.url)
      if (this.$attrs.hasOwnProperty('multiple')) {
        this.$emit('input', this.imagesUrl)
      } else {
        this.$emit('input', '')
      }
    }
  }
}
</script>

<style lang="scss" scoped>
  $width: 100px;
  $height: 60px;
  ::v-deep .el-upload {
    width: $width;
    height: $height;

    .el-upload-dragger {
      display: flex;
      width: 100%;
      height: 100%;
      border: none;
      background-color: #f6f6f6;
      justify-content: center;
      align-items: center;
    }
  }

  ::v-deep .el-upload-list {
    .el-upload-list__item {
      width: $width;
      height: $height;
    }
  }

  ::v-deep.disabledUpload .el-upload {
    display: none;
  }
</style>